package main;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class JdkSerializer implements ISerialize
{

	public byte[] serialize(Object obj) {
		ObjectOutputStream objectOut = null;
		try {
			ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
			objectOut = new ObjectOutputStream(bytesOut);
			objectOut.writeObject(obj);
			objectOut.flush();
			return bytesOut.toByteArray();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (objectOut != null)
				try {
					objectOut.close();
				} catch (Exception e) {
				}
		}
	}

	public <T> T unSerialize(byte[] bytes, Class<T> t) {
		if (bytes == null || bytes.length == 0)
			return null;

		ObjectInputStream objectInput = null;
		try {
			ByteArrayInputStream bytesInput = new ByteArrayInputStream(bytes);
			objectInput = new ObjectInputStream(bytesInput);
			return (T) objectInput.readObject();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (objectInput != null)
				try {
					objectInput.close();
				} catch (Exception e) {
				}
		}
	}
}
